<template>
  <div class="mx-auto bg-gray-50 relative">
    <div class="flex items-center justify-between px-6 py-4 bg-white"v-if="source=='question'">
      <div class="flex-1"  >
        <el-button type="primary" round :icon="Plus" @click="toCreateQuestion"> 创建题目 </el-button>
        <!--批量导入  -->
         <el-dropdown trigger="click" class="mx-4 ">
            <el-button  round>批量导入</el-button>
            <template #dropdown>
              <el-dropdown-menu class="import-dropdown">
                <el-dropdown-item @click="importTemplate('excel')">模板导入</el-dropdown-item>
                <el-dropdown-item @click="importTemplate('ai')">智能导入</el-dropdown-item>
                <el-dropdown-item @click="importTemplate('across')">跨课导入</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        <el-button round @click="handleCreateDir">新建文件夹</el-button>
      </div>
      <div class="flex-1 flex items-center justify-end gap-4 right-div">
        <el-checkbox v-model="isShowDetail" label="显示题目详情" size="large"  @change="handleIsShowDetailChange"/>
        <div class="flex items-center gap-4">
          <span class="text-blue-900/75 whitespace-nowrap text-sm">
            <font-awesome-icon :icon="['fas', 'shield']"  />
            安全设置
          </span>
          <span class="text-blue-900/75 whitespace-nowrap text-sm" @click="questionTypeDialogVisible=!questionTypeDialogVisible">
            <font-awesome-icon :icon="['fas', 'gear']"  />
            题型管理
          </span>
      
              <el-dropdown trigger="hover">
            <!-- <el-button  link>导出全部</el-button> -->
                 <span class="text-blue-900/75 whitespace-nowrap text-sm">
                   <font-awesome-icon :icon="['fas', 'arrow-up-from-bracket']"  />
                 导出全部
                </span>
                <template template #dropdown>
                  <el-dropdown-menu class="import-dropdown">
                    <el-dropdown-item @click="exportTemplate('word')">导出word</el-dropdown-item>
                    <el-dropdown-item @click="exportTemplate('excel')">导出Excel</el-dropdown-item>
                    <el-dropdown-item @click="exportTemplate('pdf')">导出PDF</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
          </el-dropdown>
      
        </div>
        <a
          target="_blank"
          href="https://ai-que.com/"
          class="w-[96px] h-[34px] hover:no-underline"
        >
          <img
            src="@/assets/img/ai-que-icon.png"
            alt=""
            class="w-full h-full"
          />
        </a>
        <el-input v-model="keyWord" placeholder="搜索" style="width: 200px">
        </el-input>
        <el-icon  class="z-10 text-gray-400 absolute right-[30px] top-[43px] text-xl">  <Search /></el-icon>
      </div>
    </div>
    <div class="flex items-center justify-between px-6 py-4 bg-white" v-if="source=='paper'">
      <div >
         <button class="px-2 py-1 rounded-br-lg " @click="handleBack">
                <font-awesome-icon icon="fas fa-reply" class="text-md mr-2 text-gray-400 hover:text-blue-400"></font-awesome-icon>返回
            </button>
        <span>从题库选题</span>
      </div>
      <div class="flex-1 flex items-center justify-end gap-4 right-div" >
        <el-checkbox v-model="isShowDetail" label="显示题目详情" size="large"  @change="handleIsShowDetailChange"/>
         <el-input v-model="keyWord" placeholder="搜索" style="width: 200px">
        </el-input>
        <el-icon  class="z-10 text-gray-400 absolute right-[30px] top-[28px] text-xl">  <Search /></el-icon>
      </div>
    </div>
    <!-- 筛选区域 -->
    <div class="px-6 py-2 bg-white   text-sm  ">
      <div class="flex items-center  flex-wrap gap-6 :md:space-x-0">
        <div class="flex items-center space-x-2">
          <span class="text-gray-600 whitespace-nowrap">课程:</span>
          <el-select
            v-model="filterData.courses"
            placeholder="请选择"
            class="w-40"
            multiple
            clearable
            collapse-tags
            :max-collapse-tags="1"
            popper-class="custom-header">
            <template #header>
              <div class="right-div mb-4">
                <el-input v-model="courseKeyWord" placeholder="搜索" style="width: 200px" ></el-input>
                <el-icon class="z-10 text-gray-400 absolute right-[20px] top-[16px] text-sm"><Search /></el-icon>
                </div>
                 <el-checkbox
                    v-model="checkAllCourse"
                    :indeterminate="indeterminate"
                    @change="handleCheckAllCourse">
                    全选
                  </el-checkbox>
            </template>
            <el-option   v-for=" course in courseList" :label="course.name" :key="course.id" :value="course.name"></el-option>
          </el-select>
        </div>
        <div class="flex items-center space-x-2">
          <span class="text-gray-600 whitespace-nowrap">题型:</span>
          <el-select v-model="filterData.questionType" placeholder  ="全部题型"  class="w-40">
            <el-option label="全部题型" value="all" />
            <el-option label="单选题" value="single" />
            <el-option label="多选题" value="multiple" />
          </el-select>
        </div>
        <div class="flex items-center space-x-2">
          <span class="text-gray-600 whitespace-nowrap">知识点:</span>
          <el-select v-model="filterData.knowledge"  placeholder="请选择" class="w-40">
            <el-option label="进程管理" value="process" />
            <el-option label="内存管理" value="memory" />
          </el-select>
        </div>
        <div class="flex items-center  space-x-2">
          <span class="text-gray-600 whitespace-nowrap">标签:</span>
          <el-select
            v-model="filterData.tags"
            placeholder="请选择"
            class="w-40"
          >
            <el-option label="基础" value="process" />
            <el-option label="线程" value="memory" />
          </el-select>
        </div>
        <div class="flex items-center space-x-2">
          <span class="text-gray-600 whitespace-nowrap">正确率:</span>
          <el-input v-model="filterData.correctRateStart" class="w-20"  placeholder="请输入"/>
          <span class="text-gray-300 whitespace-nowrap">%—%</span>
          <el-input
            v-model="filterData.correctRateEnd"
            class="w-20"
            placeholder="请输入"
          />
        </div>
        <el-button type="primary" class="ml-4 w-20" round>筛选</el-button>
      </div>
    </div>
    <!-- 表格上方的面包屑 -->
    <div class="px-6 py-2 bg-white text-gray-400 flex justify-between text-sm mt-4">
       <div class="ml-4 flex items-center text-gray-600">
          <span v-if="currentFolder" class="cursor-pointer text-gray-400 flex items-center" @click="goBack">
            <el-icon><Back /></el-icon>返回
          </span>
          <span class="mx-2 text-gray-400" v-show="currentFolder?.title">/</span>
          <span class="text-gray-400">{{ currentFolder ? currentFolder.title : '全部题目' }}</span>
        </div>
      <span>共{{ currentFolder ? currentFolder.subCount : total }}题</span>
    </div>
    <!-- 表格 -->
     <!-- {{selectedIds}} -->
    <div class="px-6 py-2 bg-white">
      <el-table 
         ref="multipleTableRef"
        :data="filteredItems"  
        stripe 
        style="width: 100%" 
        @cell-mouse-enter="handleCellMouseEnter"  
         @selection-change="handleSelectionChange"
        row-class-name="cursor-pointer" >
        <el-table-column type="selection" width="55" :selectable="selectable" />
        <el-table-column label="序号" width="70" >
           <template #default="scope">
            <div v-if="scope.row.type=='folder'">
              <font-awesome-icon :icon="['fas', 'folder']" class="text-blue-400 text-xl"/>
            </div>
            <div v-else>
              {{ getQuestionIndex(scope.$index) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="文件夹/题目"  width="400" >
          <template #default="scope">
            <div @click="handleRowClick(scope.row)">
              <!-- 遍历的是文件夹 -->
              <div v-if="scope.row.type=='folder'" class="flex items-center  justify-between">
                <div  class="flex items-center space-x-2">
                  <!-- <font-awesome-icon :icon="['fas', 'folder']" class="mr-3 text-blue-400 text-xl"/> -->
                 <div class="flex flex-col px-1" >
                  <div v-if="scope.row.isEditing" class="flex items-center space-x-2">
                    <el-input 
                    v-model="scope.row.title" 
                    placeholder="输入文件夹名称"
                    @keyup.enter="confirmFolder(scope.row,$event)"></el-input>
                    <el-button type="success" link @click="confirmFolder(scope.row,$event)">
                      <FontAwesomeIcon icon="check" size="sm"></FontAwesomeIcon>
                    </el-button>
                    <el-button type="danger" link  @click="cancelFolder(scope.row,$event)"> 
                      <FontAwesomeIcon icon="xmark" size="sm"></FontAwesomeIcon>
                    </el-button>
                   </div>
                  <span class="font-medium  whitespace-nowrap" v-if="!scope.row.isEditing">{{ scope.row.title }}</span>
                  <p class="text-gray-500" v-if="scope.row.isPublic && !scope.row.isEditing">公开</p>
                  </div>
                  <div class="border border-gray-300 px-3" v-if="!scope.row.isEditing">共{{scope.row.subCount}}题</div>
                </div>
                    <!-- 相关编辑的选项 -->
                <div v-if="isShowOption == scope.row.id && !scope.row.isEditing&&source=='question'" class="flex items-center space-x-2">
                  <el-button type="primary" link @click="handleReName(scope.row,$event)">重命名</el-button>
                  <!-- <el-button type="primary" link>更多</el-button> -->
                  <div  @click.stop>
                    <el-dropdown trigger="hover" class="mx-4 " >
                    <el-button  type="primary" link round>更多</el-button>
                    <template #dropdown>
                      <el-dropdown-menu class="import-dropdown">
                        <el-dropdown-item   v-for="item in moreOptions2"  @click="handleMoreOption(item.command,scope.row,$event)">{{ item.label }}</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
                </div>

              </div>
              <!-- 遍历的是题目 -->
              <div v-else>
                <div class="flex items-center justify-between w-full" >
                  <span> {{ scope.row.title }} </span>
                  <!-- 相关编辑的选项 -->
                  <div v-if="isShowOption == scope.row.id&&source=='question'" class="flex items-center space-x-2" >
                    <el-button type="primary" link @click="handleEdit(scope.row,$event)">编辑</el-button>
                    <!-- <el-button type="primary" link>更多</el-button> -->
                    <div  @click.stop> 
                      <el-dropdown trigger="hover" class="mx-4 ">
                      <el-button  type="primary" link round>更多</el-button>
                      <template #dropdown>
                        <el-dropdown-menu class="import-dropdown">
                          <el-dropdown-item   v-for="item in moreOptions"  @click="handleMoreOption(item.command,scope.row,$event)">{{ item.label }}</el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                    </div>
                    
                  </div>
                </div>
               <!-- 显示答案 -->
                <div v-show="isShowDetail" >
                    <ul>
                      <li v-for="item  in scope.row.options" class="mb-1">
                        <span>{{item.option}} : </span> 
                        <span>{{item.content}}</span>
                      </li>
                    </ul>
                    <div class="mt-2"> 
                      <b>答案:</b>
                      <span v-for="item in scope.row.answer"> {{ item }}</span>  
                    </div>
                </div>
              </div>
              </div>
          </template>
        </el-table-column>
        <el-table-column label="题型" >
          <template #default="scope">
            <div v-if="!scope.row.questionType" >-</div>
            <div v-else>{{ scope.row.questionType }}</div>
          </template>
        </el-table-column>
        <el-table-column label="难易">
           <template #header>
             <el-dropdown trigger="click" >
               <span class="el-dropdown-link text-gray-500/80">
                  难易<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </span>
              <template #dropdown>
                <el-dropdown-menu class="import-dropdown max-h-40">
                   <el-dropdown-item   @click="byDifficultySort('all')">全部</el-dropdown-item>
                  <el-dropdown-item   v-for="item in difficulties" @click="byDifficultySort(item.value)">{{ item.value }}({{ item.label }})</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
        </template>
          <template #default="scope">
            <div v-if="!scope.row.difficulty" >-</div>
            <div v-else>{{ scope.row.difficulty }}</div>
          </template>
        </el-table-column>
        <el-table-column label="使用量" >
            <template #default="scope">
            <div v-if="!scope.row.usage" >-</div>
            <div v-else>{{ scope.row.usage }}</div>
          </template>
        </el-table-column>
        <el-table-column label="正确率" sortable >
          <template #default="scope">
            <div v-if="!scope.row.correctRate" >-</div>
            <div v-else>{{ scope.row.correctRate }}</div>
          </template>
        </el-table-column>
        <el-table-column label="创建者" prop="creator" >
           <template #header>
             <el-dropdown trigger="click" >
               <span class="el-dropdown-link text-gray-500/80">
                  创建者<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </span>    
              <template #dropdown>
                <el-dropdown-menu class="import-dropdown max-h-40">
                  <el-dropdown-item   @click="byCreatorSort('all')">全部</el-dropdown-item>
                  <el-dropdown-item   v-for="item in creatorList" @click="byCreatorSort(item.name)">{{ item.name }}</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>  
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime"  sortable/>
      </el-table>

      <!-- 分页 --> 
      <div class="flex justify-end px-6 py-4">
        <el-pagination 
          v-model:current-page="currentPage"  
          v-model:page-size="pageSize" 
          :total="total" 
          :page-sizes="[30, 50, 100]" 
          layout="total, sizes, prev, pager, next" />
      </div>
    </div>
    <!-- 是否是试卷要选择题目 -->
  <el-affix position="bottom" :offset="20" v-if="source=='paper'">
    <div class=" bg-white flex justify-between px-6 py-4">
      <div class="flex items-center space-x-4">
        <span>已选{{ multipleSelection.length }}题</span>
        <div class="text-gray-400 text-[12px] space-x-1">
        <span v-for="item in questionTypeCounts">{{item.count}}{{item.questionType}}</span>
        </div>
      </div>
      <div>
        <el-button  round class="w-20" @click="toggleSelection()">取消选择</el-button>
        <el-button type="primary" round class="w-20" @click="completeSelection">完成选题</el-button>
      </div>

    </div>
  </el-affix>
    <!-- 模版导入的弹出框 -->
   <el-dialog v-model="importTemplateDialogVisible" title="导入模版" width="40%" class="rounded-lg">
    <div class="p-4 flex items-center justify-between">
      <a href="#"><el-icon><Download /></el-icon> Excel模版下载</a>
      <div>
       <el-checkbox v-model="updateExisting" label="导入重复题目跟新原题" size="large" />
      <el-checkbox v-model="keepFolder" label="导入ti文件保留文件夹" size="large" />
     </div>
    </div>
     <el-upload
        class="upload-demo"
        drag
        :auto-upload="false"
        :show-file-list="false"
        :on-change="handleChange"
        multiple
      >
  <div class="el-upload__text mb-6">
      将excel文件拖拽到此区域 
      <p>——或——</p>
    </div>
    <el-button :icon="UploadFilled" type="primary" round>上传文件</el-button>
    
  </el-upload>
   </el-dialog>
   <!-- 题型管理的弹出框 -->
    <el-dialog v-model="questionTypeDialogVisible" title="题型管理" width="40%" class="rounded-lg">
      <!-- 表格内容 -->
      <div class="px-6 py-4">
        <el-table :data="questionTypes" style="width: 100%" :border="false">
          <el-table-column prop="name" label="题型名称" width="200">
            <template #default="{ row }">
              <div v-if="row.isEditing" class="flex items-center">
                <el-input
                  v-model="row.editingName"
                  class="mr-2"
                  size="small"
                  placeholder="请输入题型名称"
                  @keyup.enter="confirmRename(row)"
                />
                <div class="flex gap-2">
                  <el-icon class="cursor-pointer text-blue-500" @click="confirmRename(row)">
                    <Check />
                  </el-icon>
                  <el-icon class="cursor-pointer text-gray-400" @click="cancelRename(row)">
                    <Close />
                  </el-icon>
                </div>
              </div>
              <span v-else>{{ row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="类型" width="200" />
          <el-table-column label="操作">
            <template #default="{ row }">
              <div class="flex items-center gap-4">
                <el-button
                  v-if="!row.isEditing"
                  type="primary"
                  link
                  @click="startRename(row)"
                >
                  重命名
                </el-button>
                <el-button
                  v-if="row.canDelete"
                  type="primary"
                  link
                  @click="deleteType(row)"
                >
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 底部操作按钮 -->
        <template #footer>
          <div class="px-6 py-4 border-t flex items-center justify-between">
            <el-button
              type="primary"
              link
              class="flex items-center"
              @click="addNewType"
            >
              <el-icon class="mr-1">
                <Plus />
              </el-icon>
              新建题型
            </el-button>
            <div class="flex gap-4">
              <el-button @click="questionTypeDialogVisible=false">取消</el-button>
              <el-button type="primary" @click="confirmDialog">确定</el-button>
            </div>
          </div>
        </template>
    </el-dialog>
    <!-- 导出全部的弹框 -->
    <el-dialog v-model="exportAllDialogVisible" :title="exportTitle" width="30%" class="rounded-lg"> 
      
      <el-checkbox-group v-model="exportOptions" class="flex flex-col gap-4 pl-6" v-if="exportType=='word' || exportType=='pdf'">
        <el-checkbox label="包含答案" value="answer"></el-checkbox>
        <el-checkbox label="包含解析" value="analysis"></el-checkbox>
        <el-checkbox label="包含难易度" value="difficulty"></el-checkbox>
        <el-checkbox label="包含题型名称" value="typeName"></el-checkbox>
        <el-checkbox label="包含知识点" value="point"></el-checkbox>
      </el-checkbox-group>
      <!-- 导出完整题目内容单选 -->
      <el-radio-group v-model="exportFormat" class="grid  ml-6"  v-else-if="exportType=='excel'">
        <el-radio value="all">导出完整题目内容</el-radio>
        <el-radio value="txt">导出纯文本题目内容</el-radio>
          <!-- 说明文字，针对纯文本选项 -->
        <span class="text-gray-400 text-[10px] ml-6">
          勾选后，将过滤html标签、图片及数学符号
        </span>
      </el-radio-group>
      <template #footer>
        <div class="px-6 py-4 border-t flex items-center gap-8 justify-end">
          <el-button @click="exportAllDialogVisible=false" round>取消</el-button>
          <el-button type="primary" @click="confirmExportDialog" round>确定</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 移动到的弹框 -->
    <el-dialog v-model="moveDialogVisible"  width="30%" class="rounded-lg"> 
         <template #header="{ close, titleId, titleClass }">
          <div class="my-header">
            <h4 :id="titleId" :class="titleClass">
              选择目录
              <span class="text-sm text-gray-400">(选择目标目录)</span>
            </h4>
            
          </div>
        </template>

      <!-- 目录列表 -->
      <div class="min-h-[300px] max-h-[400px] overflow-y-auto p-4 text-xl">
    
    <el-tree
          ref="treeRef"
          :data="treeData"
          :props="defaultProps"
          node-key="id"
          :default-expanded-keys="[1]"
          @node-click="handleNodeClick"
        >
          <template #default="{ node, data }">
            <div class="flex items-center">
              <el-icon class="mr-2 text-blue-400">
                <Folder />
              </el-icon>
              <span v-if="!data.isEditing">{{ node.label }}</span>
              <div class="flex items-center" v-if="data.isEditing">
               <el-input  v-model="data.editingName" class="ml-2 w-[100px]" size="small" />
               <el-button  class="w-4 h-4 p-2 mx-4" @click="createNodeFolder(data)">
                <FontAwesomeIcon icon="fa-solid fa-check"  class=" cursor-pointer text-blue-500"/>
               </el-button>
               <el-button  class="w-4 h-4 p-2 mx-4" @click="cancelNodeFolder(data)">
                <FontAwesomeIcon icon="fa-solid fa-xmark" class="cursor-pointer text-blue-500"/>
              </el-button>
              </div>
              <el-icon v-if="selectedNode === data.id && !data.isEditing" class="ml-2 text-blue-500" >
                <!-- <Select /> -->
                <Star />
              </el-icon>
            </div>
          </template>
        </el-tree>
         </div>
      <!-- 底部操作按钮 -->
        <template #footer>
          <div class="px-6 py-4 border-t flex items-center justify-between">
            <el-button
              type="primary"
              link
              class="flex items-center"
              @click="addNodeFolder"
            >
              <el-icon class="mr-1">
                <Plus />
              </el-icon>
              新建文件夹
            </el-button>
            <div class="flex gap-4">
              <el-button @click="moveDialogVisible=false" round class="w-20">取消</el-button>
              <el-button type="primary" @click="confirmMoveDialog" round class="w-20">确定</el-button>
            </div>
          </div>
        </template>
    </el-dialog>
    <!-- 删除的弹出框 -->
     <el-dialog v-model="deleteDialogVisible" title="删除"  width="20%" class="rounded-lg">  
      <div class="text-base py-4 px-2 text-gray-500">删除后可在回收站内恢复题目,确认删除？</div>
         <template #header="{ close, titleId, titleClass }">
          <div class="my-header border-b pb-4">
            <span :id="titleId" :class="titleClass">
              删除
            </span>
            
          </div>
        </template>
      <template #footer>
          <div class="py-4 px-6 border-t flex items-center justify-end">
            <div class="flex gap-4">
              <el-button @click="deleteDialogVisible=false" round class="w-20"> 取消 </el-button>
              <el-button type="primary" @click="deleteItem" round class="w-20"> 确定 </el-button>
            </div>
          </div>
        </template>
     </el-dialog> 
    <!-- 锁定的弹出框 -->
     <el-dialog v-model="lockDialogVisible" title="删除"  width="25%" class="rounded-lg">  
      <div class="text-base py-4 px-2 text-gray-500">锁定后，题目将放入“已锁定题目”文件夹，已锁定题目将不会出现在题库选题和随机组卷中。确认锁定？</div>
         <template #header="{ close, titleId, titleClass }">
          <div class="my-header border-b pb-4">
            <span :id="titleId" :class="titleClass">
              提示
            </span>
            
          </div>
        </template>
      <template #footer>
          <div class="py-4 px-6 border-t flex items-center justify-end">
            <div class="flex gap-4">
              <el-button @click="lockDialogVisible=false" round class="w-20"> 取消 </el-button>
              <el-button type="primary" @click="handleLockOption" round class="w-20"> 确定 </el-button>
            </div>
          </div>
        </template>
     </el-dialog> 
    <!-- 修改难以程度的模态框 -->
    <el-dialog v-model="difficultyDialogVisible" title="修改难度"  width="30%" class="rounded-lg">
         <template #header="{ close, titleId, titleClass }">
          <div class="my-header border-b pb-4">
            <span :id="titleId" :class="titleClass">
              修改难易度
            </span>    
          </div>
        </template>
        <el-radio-group v-model="difficulty" class="grid  space-y-2 ml-6   max-h-[200px] overflow-y-auto">
          <el-radio v-for="item in difficulties" :key="item.id" :value="item.value">{{ item.value }}({{ item.label }})</el-radio>
        </el-radio-group>
      <template #footer>
          <div class="py-4 px-6 border-t flex items-center justify-end">
            <div class="flex gap-4">
              <el-button @click="difficultyDialogVisible=false" round class="w-20"> 取消 </el-button>
              <el-button type="primary" @click="modifyDifficulty" round class="w-20"> 确定 </el-button>
            </div>
          </div>
        </template>

    </el-dialog>
    <!-- 修改题型-->
     <el-dialog v-model="modifyTypeDialogVisible" title="修改题型"  width="40%" class="rounded-lg">
         <template #header="{ close, titleId, titleClass }">
          <div class="my-header ">
            <span :id="titleId" :class="titleClass">
              修改题型
            </span>    
          </div>
        </template>
        <div class="border-y border-gray-200 p-2">
          <span class="text-gray-400   whitespace-nowrap">仅支持修改为同类型的其他题型。如简答题，可修改为同为简答题类型的论述题、计算题等</span>
        </div>
        <el-table :data="questionTypes" style="width: 100%" >
          <el-table-column prop="name" label="题型名称" >
            <template #default="{ row }">
              <div v-if="row.isEditing" class="flex items-center">
                <el-input
                  v-model="row.editingName"
                  class="mr-2"
                  size="small"
                  placeholder="请输入题型名称"
                  @keyup.enter="confirmRename(row)"
                />
                <div class="flex gap-2">
                  <el-icon class="cursor-pointer text-blue-500" @click="confirmRename(row)">
                    <Check />
                  </el-icon>
                  <el-icon class="cursor-pointer text-gray-400" @click="cancelRename(row)">
                    <Close />
                  </el-icon>
                </div>
              </div>
              <span v-else>{{ row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="类型" />
        </el-table>
        <template #footer>
          <div class="py-4 px-6 flex items-center justify-between">
               <el-button
              type="primary"
              link
              class="flex items-center"
              @click="addNewType"
            >
              <el-icon class="mr-1">
                <Plus />
              </el-icon>
              新建题型
            </el-button>
            <div class="flex gap-4">
              <el-button @click="modifyTypeDialogVisible=false" round class="w-20"> 取消 </el-button>
              <el-button type="primary" @click="handleModifyType" round class="w-20"> 确定 </el-button>
            </div>
          </div>
          </template>
     </el-dialog>
    <!-- 权限设置-->
     <el-dialog v-model="modifyPermissionDialogVisible" title="权限设置"  width="30%" class="rounded-lg">
         <template #header="{ close, titleId, titleClass }">
          <div class="my-header ">
            <span :id="titleId" :class="titleClass">
              权限设置
            </span>    
          </div>
        </template>
          <!-- 共享范围设置区域 -->
          <div class="mb-8 ml-2">
            <p class="text-base mb-4">共享范围设置</p>
            <el-radio-group v-model="permission" class="grid  space-y-8 ml-6  ">
              <el-radio value="private" >
                私有
                <p class="text-sm text-gray-400 absolute">仅自己可见。文件夹中只能添加自己创建的题目</p>
              </el-radio>
              <el-radio value="public" >
                公开
                <p class="text-sm text-gray-400  absolute ">所有教学团队成员可见。文件夹中可添加其他成员创建的题目</p>
              </el-radio>
            </el-radio-group>
          </div>

          <!-- 学生自测设置区域 -->
          <div class="ml-2">
            <p class="text-base  mb-2">学生自测设置</p>
            <el-checkbox v-model="allowStudentTest" class="ml-6">
              允许学生从此文件夹中抽题自测
            </el-checkbox>
          </div>
        
        <template #footer>
          <div class="py-4 px-6 flex items-center justify-end">
            <div class="flex gap-4">
              <el-button @click="modifyPermissionDialogVisible=false" round class="w-20"> 取消 </el-button>
              <el-button type="primary" @click="handleModifyPermission" round class="w-20"> 确定 </el-button>
            </div>
          </div>
          </template>
     </el-dialog>
    <!-- 关联知识点-->
     <el-dialog v-model="knowledgeDialogVisible" title="关联知识点"   width="40%" class="rounded-lg">
         <template #header="{ close, titleId, titleClass }">
          <div class="my-header">
            <span :id="titleId" :class="titleClass">
              关联知识点
            </span>    
          </div>
        </template>
      <div class="flex border-t border-b border-gray-200 min-h-[300px] overflow-y-auto">
        <!-- 添加知识点 -->
        <div class="py-4 w-[70%]">
          <div class="flex justify-between right-div pr-4">
            <el-button link  type="primary"  @click="addNewKnowledge">添加知识点</el-button>
            <div class="relative">
              <el-input v-model="searchKnowledge" placeholder="搜索" class="w-40" size="small" />
              <el-icon class="z-10 text-gray-400 absolute right-[10px] top-[8px] text-sm"><Search /></el-icon>
            </div>
          </div>
           <ul>
              <li v-for="item in knowledgeList" :key="item.id" class="p-2 flex items-center justify-between cursor-pointer hover:bg-blue-50" 
              @mouseenter="item.showActions = true"
              @mouseleave="item.showActions = false">
                <span  v-if="!item.isEditing">{{item.name}}</span>
                <div v-if="item.isEditing" class="flex items-center space-x-2 pr-2">
                  <el-input v-model="item.editingName" class="w-[100px] "  @keyup.enter="confirmRename(row)" />
                  <div class="flex gap-2 ">
                    <el-icon class="cursor-pointer text-blue-500" @click="confirmRename(item)">
                      <Check />
                    </el-icon>
                    <el-icon class="cursor-pointer text-gray-400" @click="cancelRename(item)">
                      <Close />
                    </el-icon>
                  </div>
                </div> 
                <div class="flex items-center space-x-2 pr-2">
                  <el-button link type="info" class=""  @click="startRename(item)"  v-show="item.showActions" >编辑</el-button>
                  <el-button link type="info" class="" @click="deleteKnowledge(item)"  v-show="item.showActions">删除</el-button>
                  <el-checkbox v-model="item.isChecked" ></el-checkbox>
                </div>
              </li>
            </ul>
        </div>
        <!--已选知识点  -->
        <div class="p-4  border-l w-[300px]">
          <span class="text-gray-400">已选 {{ selectedKnowledges.length }}个</span>
           <div class="flex flex-wrap space-x-2">
              <div class="mt-4 border border-dashed border-blue-200 p-2 h-10 text-center " v-for="item in selectedKnowledges" :key="item.id">
                <span class="text-gray-400">{{ item.name }}</span>
              </div>
            </div>
        </div>
      </div>  
        
      <template #footer>
          <div class="px-6 flex items-center justify-between">
          <el-checkbox v-model="isSyncQuestion" label="同步修改引用此题目的作业和考试" size="large" />
            <div class="flex gap-4">
              <el-button @click="knowledgeDialogVisible=false" round class="w-20"> 取消 </el-button>
              <el-button type="primary" @click="addKnowledgeToQuestion" round class="w-20"> 确定 </el-button>
            </div>
          </div>
        </template>

    </el-dialog>
    <!-- 关联标签-->
    <el-dialog v-model="addTagDialogVisible"   width="40%" class="rounded-lg">
         <template #header="{ close, titleId, titleClass }">
          <div class="my-header">
            <span :id="titleId" :class="titleClass">
              添加标签
            </span>    
          </div>
        </template>
        <div class="flex border-t border-b border-gray-200 min-h-[300px] overflow-y-auto"> 
          <!-- 标签的展示和添加区域 -->
          <div class="py-4 w-[70%]">
            <el-button link  type="primary" class="text-base" @click="addNewTag">添加标签</el-button>
            <ul>
              <li v-for="item in tagList" :key="item.id" class="p-2 flex items-center justify-between cursor-pointer hover:bg-blue-50" 
              @mouseenter="item.showActions = true"
              @mouseleave="item.showActions = false">
                <span v-if="!item.isEditing">{{item.name}}</span>
                <div v-if="item.isEditing" class="flex items-center space-x-2 pr-2">
                  <el-input v-model="item.editingName" class="w-[100px] "  @keyup.enter="confirmRename(row)" />
                  <div class="flex gap-2 ">
                    <el-icon class="cursor-pointer text-blue-500" @click="confirmRename(item)">
                      <Check />
                    </el-icon>
                    <el-icon class="cursor-pointer text-gray-400" @click="cancelRename(item)">
                      <Close />
                    </el-icon>
                  </div>
                </div> 
                <div class="flex items-center space-x-2 pr-2">
                  <el-button link type="info" class=""  @click="startRename(item)"  v-show="item.showActions" >编辑</el-button>
                  <el-button link type="info" class="" @click="deleteTag(item)"  v-show="item.showActions">删除</el-button>
                  <el-checkbox v-model="item.isChecked" ></el-checkbox>
                </div>
              </li>

            </ul>
          </div>
          <!-- 关联到的标签区域 -->
          <div class="p-4  border-l  w-[300px]">
            <span class="text-gray-400">已选 {{ selectedTags.length }}个</span>
            <div class="flex flex-wrap space-x-2">
              <div class="mt-4 border border-dashed border-blue-200 p-2 h-10 text-center " v-for="item in selectedTags" :key="item.id">
                <span class="text-gray-400">{{ item.name }}</span>
              </div>
            </div>
          </div>

        </div>
          
        <template #footer>
            <div class="py-4 px-6  flex items-center justify-end">
              <div class="flex gap-4">
                <el-button @click="addTagDialogVisible=false" round class="w-20"> 取消 </el-button>
                <el-button type="primary" @click="addTagToQuestion" round class="w-20"> 确定 </el-button>
              </div>
            </div>
          </template>

    </el-dialog>
  </div>  
</template>

<script setup>
import { ref,reactive,onMounted,computed ,watch,toRefs} from "vue"
import { Plus, Search,Download, UploadFilled,Select,Star,ArrowDown } from "@element-plus/icons-vue"
import  { getDifficultyList, getQuestionList } from "@/api/questions.js"
import { ElMessageBox,ElMessage } from "element-plus";
import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome";
import { useRouter } from "vue-router"
import { useTabsStore } from "@/store/tabs";

// 
const  props = defineProps({
    source: { type: String, default: "question" },
    isSelect: { type: Boolean, default: false },
    selectedQuestions: { type: Object, default: () => ({}) },
    selectedIds: { type: Array, default: () => [] },
})
const emit=defineEmits(['update:selectedQuestions','update:isSelect'])
const  {source,selectedIds} =toRefs(props)
const router = useRouter()
const  tabsStore = useTabsStore()


//是否显示题目详情
const isShowDetail = ref(false)
//搜索的关键词
const keyWord = ref("")
//筛选的条件
const filterData = reactive({
  courses: [],
  questionType: "",
  knowledge: "",
  tags: [],
  correctRateStart: "",
  correctRateEnd: "",
})
//当前页
const currentPage = ref(1)
//每页显示多少条数据
const pageSize = ref(30)
//总条数
const total = ref(10)
//题库列表
const questionList = ref([]);
const importTemplateDialogVisible = ref(false)
// 题目难以程度
const  difficulties = ref([])
//获取所有的题库 
const getQuestionData = async () => {
  // 获取问题列表
   getQuestionList(currentPage.value, pageSize.value, filterData).then(res => { 
    // 输出响应结果
    console.log(res)
    // 更新问题列表
    questionList.value = res.data.data
    // 更新总数
    total.value = res.data.total
      console.log('备选题目',selected.value);
      // console.log(filteredItems.value.includes(selected.value[0]));
      toggleSelection(selected.value,true)
     
  }) 
}
const selected =computed(()=>{
  return filteredItems.value.filter(item=>selectedIds.value.includes(item.id))
})
onMounted(async () => { 
 await getQuestionData()
  getDifficultyList().then(res => {
    difficulties.value = res.data.data
  })
  console.log(multipleSelection.value,'---');
  
})



//点击创建试题的按钮
const  toCreateQuestion = () => { 
  tabsStore.addTab({
      name: 'CreateQuestion',
      title: '创建题目',
    });
  // tabsStore.addTab({ title: "编辑题目", path: "/questionOption/create-question" })
  router.push({ name: "CreateQuestion" })
}

//是否显示操作的选项
const isShowOption = ref();
// 鼠标移入行
const handleCellMouseEnter = (row, col, cell, event) => {
  isShowOption.value = row.id;
};


/**************检索区域的操作*************** */
// 根据课程检索
const courseKeyWord=ref('')
const courseList=ref([
  { id: 1, name: "计算机基础" },
  { id: 2, name: "操作系统" },
  { id: 3, name: "数据库" }
])
const checkAllCourse = ref(false)
const indeterminate = ref(false)
// const  selectedCourseList = ref([])
const  handleCheckAllCourse=(val)=>{
    indeterminate.value = false
  if (val) {
    filterData.courses = courseList.value.map((_) => _.name)
  } else {
    filterData.courses = []
  }
}

watch(()=>filterData.courses, (val) => {
  console.log(val.length, 'filterData.courses变化了')
  if (val.length === 0) {
    checkAllCourse.value = false
    indeterminate.value = false
  } else if (val.length === courseList.value.length) {
    checkAllCourse.value = true
    indeterminate.value = false
  } else {
    indeterminate.value = true
  }
})

// 根据难度检索
const  byDifficultySort = (difficulty) => {
 console.log(difficulty,'根据难度检索')
};
//  题目创建者列表
const  creatorList = ref([
  { id: 1, name: "沈涵之" },
  { id: 2, name: "陆泽明" },
  { id: 3, name: "刘丽" }
])
//  根据创建者检索
const byCreatorSort = (creator) => {
  console.log(creator,'根据创建者检索') 
}


  

// 试题编辑按钮被点击
const handleEdit = (row,event) => {
  console.log(row, "编辑按钮被点击");
  // todo 跳转到试题编辑的页面  试题编辑和创建试题共用一套页面，通过路由参数区分是编辑还是创建
  event.stopPropagation();
   tabsStore.addTab({
      name: 'CreateQuestion',
      title: '编辑题目',
    });

  router.push({ name: "CreateQuestion", params: { id: row.id } });

};

// 显示题目详情
const handleIsShowDetailChange = ()=> {
  console.log("显示题目详情按钮被点击",isShowDetail.value);
};


// 计算当前显示的题目和文件夹
const filteredItems = computed(() => {
  if (!currentFolder.value) {
    // 根目录显示所有没有父级的项目
    return questionList.value.filter(item => !item.parentId);
  }
  // 显示当前文件夹下的项目
  return questionList.value.filter(item => item.parentId === currentFolder.value.id);
});

// 当前文件夹
const  currentFolder = ref(null)
const  editingFolder = ref(null)
// 点击的是否是重名
const isRename  = ref(false)

// 计算题目序号
const getQuestionIndex = (index) => {
   // 过滤出当前页所有题目
  const currentPageQuestions = filteredItems.value.filter(item => item.type !== 'folder');
  const currentPageFolder = filteredItems.value.filter(item => item.type == 'folder');
  const  folderLength = currentPageFolder.length

  // 获取当前行在当前页题目中的索引
  const currentQuestionIndex = index-folderLength
  // console.log(currentQuestionIndex,'当前题目在当前页的索引')
  // 计算序号，第一页从 1 开始，后续页码按顺序叠加
  return (currentPage.value - 1) * pageSize.value + currentQuestionIndex + 1;
}

watch(currentFolder, () => {
  currentPage.value = 1;
});

//点击新建文件夹的按钮
/** 处理创建文件夹的点击事件 */
const   handleCreateDir = () => {
  console.log("新建文件夹的按钮被点击");
  // 如果有正在编辑的文件夹，先取消
          if (editingFolder.value) {
            cancelFolder(editingFolder.value);
          }
          // 调用后端接口创建文件夹，此处仅为示例代码
          const newFolder = {
            id: 'temp-' + Date.now(),
            title: '',
            type: 'folder',
            isPublic:true,
            parentId: currentFolder.value ? currentFolder.value.id : null,
            createdTime: new Date().toISOString().split('T')[0],
            // updatedAt: new Date().toISOString().split('T')[0],
            subCount:0,
            isEditing: true
          };
          questionList.value.unshift(newFolder);
          editingFolder.value = newFolder;
};
 // 确认创建文件夹
 const confirmFolder = (folder,event) => {
  event.stopPropagation()
   if (!folder.title.trim()) {
      ElMessage.warning('请输入文件夹名称');
     return;
   }
   // 生成实际ID
   folder.id = 'folder-' + Date.now();
   folder.isEditing = false;
   editingFolder.value = null;
   // todo 调用后端接口创建文件夹

   ElMessage.success('文件夹创建成功');
 };
 // 重命名文件夹
 const handleReName =(row,event)=>{
  console.log("重命名被点击",row,event)
  event.stopPropagation()
  row.isEditing = true;
  isRename.value = true
  // todo调用后端接口  重命名文件夹

}
        
 // 取消创建文件夹
 const cancelFolder = (folder,event) => {
 event.stopPropagation()
 console.log('取消创建文件夹/或者取消重命名', folder,isRename.value)
 if(isRename.value) {
   folder.isEditing = false
   isRename.value = false
 }else{
   // 删除新建的文件夹 
    const index = questionList.value.findIndex(item => item.id === folder.id);
    if (index !== -1) {
      questionList.value.splice(index, 1);
    }
    editingFolder.value = null;
  };
}

 /**********题型管理的相关操作********************************************/
 // 题型管理的数据
const questionTypeDialogVisible = ref(false)
const questionTypes = ref([
  { name: '单选题', type: '单选题', isEditing: false, editingName: '', canDelete: false },
  { name: '多选题', type: '多选题', isEditing: false, editingName: '', canDelete: false },
  { name: '填空题', type: '填空题', isEditing: false, editingName: '', canDelete: false },
  { name: '判断题', type: '判断题', isEditing: false, editingName: '', canDelete: false },
  { name: '简答题', type: '简答题', isEditing: false, editingName: '', canDelete: false },
  { name: '名词解释', type: '名词解释', isEditing: false, editingName: '', canDelete: true },
])
//重名名
const startRename = (row) => {
  row.isEditing = true;
  row.editingName = row.name;
};
//确认重命名
const confirmRename = (row) => {
  if (row.editingName.trim()) {
    row.name = row.editingName;
  }
  row.isEditing = false;
};
//取消重命名
const cancelRename = (row) => {
  row.isEditing = false;
  row.editingName = row.name;
};
//删除题型  前端删除  todo  调用后端接口删除
const deleteType = (row) => {
  const index = questionTypes.value.indexOf(row);
  if (index > -1) {
    questionTypes.value.splice(index, 1);
  }
};

const addNewType = () => {
  questionTypes.value.push({
    name: '新题型',
    type: '简答题',
    isEditing: true,
    editingName: '',
    canDelete: true
  });
};
// 题型管理的确认操作
const confirmDialog = () => {
  // 确认操作逻辑
};

// 点击导出按钮相关的操作 
const   exportAllDialogVisible = ref(false)
// 默认导出的选项 
const  exportOptions = ref(['answer','analysis']);
// 导出方式 
const  exportType = ref('word');
// 导出dialog的表头
const  exportTitle = ref('导出内容')
// 导出Excel文件的设置 
const  exportFormat=ref('all')

// 导出按钮被点击
const  exportTemplate = (value) => {
  exportType.value = value;
  if (value === 'excel') { //导出的是exicel文件导出操作
    exportTitle.value = '导出设置'
  } else if (value === 'word'|| value === 'pdf') { //导出的是word或pdf
    exportTitle.value = '导出内容'
  }
    exportAllDialogVisible.value = true;
 
};
// 导出dialog的确认操作
const  confirmExportDialog=()=>{
  //todo 调用后端接口 要导出的数据格式 
  console.log(exportOptions.value,exportType.value,exportFormat.value);
  ElMessage.success('已导出');
}

// 批量导入相关的操作
const  importTemplate=(type)=>{ 
  // console.log(value,"批量导入按钮被点击")
    ElMessage.success(`已选择${type}方式`);
    if(type==="excel"){ 
      importTemplateDialogVisible.value = true;
    }else if(type==="word"){

    }
}

// 模版导入 
// 是否跟新原题
const  updateExisting=ref(false)
// 是否保留文件夹
const  keepFolder=ref(false)
// 上传的文件 
const  uploadFile=ref(null)
// 文件上传前的判断 
const   beforeUpload=(rawFile)=>{ 
  console.log(rawFile,'sdfsadfdsg')
 const isExcel = file.type.includes('excel') || 
                 file.type.includes('spreadsheetml') || 
                 /\.(xlsx|xls)$/i.test(rawFile.name);
  const isLt10M = rawFile.size / 1024 / 1024 < 10;

  if (!isExcel) {
    ElMessage.error('只能上传Excel文件!');
    return false;
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB!');
    return false;
  }
  return true;
}
// 导入模版相关操作
const handleChange=(file,fileList)=>{ 
  console.log("handleChange被调用了",file,fileList)
  uploadFile.value = file.raw
  //todo 调用后端接口  完成导入操作

}

//下拉菜单的选项
const moreOptions = reactive([
  { label: "移动到", command: "move"},
  { label: "锁定", command: "lock" },
  { label: "复制", command: "copy" },
  { label: "删除", command: "delete" },
  { label: "修改题型", command: "modifyType" },
  { label: "修改难易程度", command: "modifyLevel" },
  { label: "关联知识点", command: "knowledgePoint" },
  { label: "关联标签", command: "tags" },
  // { label: "保存到云盘", command: "saveToCloud" },
]);
const moreOptions2 = reactive([
  { label: "置顶", command: "top" },
  { label: "移动到", command: "move" },
  { label: "锁定", command: "lock" },
  { label: "复制", command: "copy" },
  { label: "删除", command: "delete" },
  { label: "权限设置", command: "permissionSetting" },
  // { label: "保存到云盘", command: "saveToCloud" },
]); 

// 模态框是否显示
const  moveDialogVisible=ref(false) //移动到
const  deleteDialogVisible=ref(false)//删除
const  deleteFileOrQue=ref(null)//复制
const  selectedRow=ref(null)//选中的行
const  difficultyDialogVisible=ref(false)//修改难度
const  knowledgeDialogVisible=ref(false)//关联知识点
const  addTagDialogVisible=ref(false)//关联标签
const  modifyTypeDialogVisible=ref(false)//修改题型
const  lockDialogVisible=ref(false)//锁定题目
const  modifyPermissionDialogVisible = ref(false)//权限设置



// 点击更多选项
const  handleMoreOption=(value,row,event)=>{ 
  console.log(value,"更多选项被点击")
  selectedRow.value=row
  event.stopPropagation()
  if(value=='move'){
    moveDialogVisible.value = true
  }else if(value=='copy'){
    moveDialogVisible.value = true
  }else if(value=='delete'){
    deleteDialogVisible.value = true
    deleteFileOrQue.value = row
  }else if(value=='modifyLevel'){
    difficultyDialogVisible.value = true
  }else if(value=='knowledgePoint'){
    knowledgeDialogVisible.value = true
  }else if(value=='tags'){
    addTagDialogVisible.value = true
  }else if(value=='modifyType'){
    modifyTypeDialogVisible.value = true
  }else if(value=='lock'){
    lockDialogVisible.value = true
  }else if(value=='permissionSetting'){
    modifyPermissionDialogVisible.value = true
  }else if(value=='saveToCloud'){
  }
}

 /******************移动到dialog的操作**************************** */
const treeRef = ref();
const selectedNode = ref();
// 目录结构数据
const treeData = ref([
  {
    id: 1,
    label: '根目录',
    children: [
      {
        id: 2,
        label: '新建文件夹'
      },
      {
        id: 3,
        label: 'java基础',
        children: [
          {
            id: 4,
            label: '基础1'
          }
        ]
      }
    ]
  }
])
const defaultProps = {
  children: 'children',
  label: 'label'
};
// 当前选中的文件夹
const handleNodeClick = (data) => {
  selectedNode.value = data.id;
};
// 添加文件夹的操作 
const  addNodeFolder =async () => {
  console.log("添加文件夹的操作",selectedNode.value)
  try {
      const newNode = {
        id: Date.now(),
        label: '',
        isEditing: true,
        editingName: ''
      };
      if (selectedNode.value) {
        const node = treeRef.value.getNode(selectedNode.value);
        node.expanded=true;
        // 如果没有子节点，则创建一个空数组作为其子节点的容器
        if (!node.data.children) {
          node.data.children = [];
        }
        // 将新节点添加到当前节点的子节点数组中
        node.data.children.push(newNode); 
      } else {//根目录下创建文件夹
        treeData.value[0].children?.push(newNode);
      }
     
  } catch {
    // 用户取消输入
  }
};
//  确定创建节点目录
const  createNodeFolder =(data)=>{
  console.log(data,"确定创建节点目录")
  if(data.editingName){
    data.isEditing = false;
    //  找到正在编辑的节点
    const editingNode  = treeRef.value.getNode(data.id);
    editingNode.data.label = data.editingName;
    // 更新正在编辑的节点的label属性，并更新节点视图
    
    // 调用后端接口创建文件夹
  }else{
    data.isEditing = false;
  }
}

// 取消创建节点目录
const  cancelNodeFolder =(data)=>{
  console.log(data,"取消创建节点目录")
  //找到正在编辑的节点
  const editingNode  = treeRef.value.getNode(data.id);
  // 移除正在编辑的节点
  editingNode.parent.removeChild(editingNode);
}

// 移动题目到文件夹的操作 
const confirmMoveDialog=()=>{
  // 被选中的节点文件夹
  const selectedFile = treeRef.value.getNode(selectedNode.value);
  console.log(selectedFile,"移动题目到文件夹的操作")
  // 调用后端接口移动题目到文件夹
}

// 删除项目
 const deleteItem = () => {
  // todo  以下删除的操作 请调用后端接口  此处的删除操作是前端模拟的
   // 检查是否有子项目
   const hasChildren = questionList.value.some(i => i.parentId === deleteFileOrQue.value.id);
   if (hasChildren) {
    ElMessage.warning('该文件夹不为空，无法删除');
     return;
   }
   questionList.value = questionList.value.filter(i => i.id !== deleteFileOrQue.value.id);
   deleteDialogVisible.value = false;
   ElMessage.success('删除成功');
 };

  /******************修改题目难易度dialog的操作**************************** */
 // 
 const  difficulty= ref();
 // 修改难以程度
 const  modifyDifficulty = () => {
  //被选中的题目
  console.log(selectedRow.value,"修改难以程度",difficulty.value)
  
  // todo 调用后端接口修改题目难度
  difficultyDialogVisible.value = false;
 };
 
 /******************关联标签dialog的操作**************************** */
// 标签数据 
const  tagList = ref([
  { id: 1, name: 'Java基础',isEditing: false,isRename:false,editingName:'',isChecked:false,showActions:false },
  { id: 2, name: '基础',isEditing: false,isRename:false,editingName:'',isChecked:false,showActions:false  },
]);
// 被选中的标签 
const  selectedTags = computed(() => tagList.value.filter(i => i.isChecked));
//  是否展示编辑和删除 
// 删除标签 
const  deleteTag = (tag) => {
  // todo 调用后端接口删除标签
  tagList.value = tagList.value.filter(i => i.id !== tag.id);
};

 // 新增标签的确定操作
 const addNewTag = () => { 
  console.log("新增标签")
  const newTag = { id: Date.now(), name: '',isEditing: true,isRename:false,editingName:'',isChecked:false };
  tagList.value.push(newTag);
 };


 //  关联标签的确定操作
 const  addTagToQuestion = () => { 
  console.log(selectedRow.value,"关联标签")

  // todo 调用后端接口关联标签
  addTagDialogVisible.value = false;
 };
 
 /******************关联知识点dialog的操作**************************** */
//  是否同步
const  isSyncQuestion = ref(false);
// 知识点列表
const  knowledgeList = ref([
  { id: 1, name: '数据',isEditing: false,isRename:false,editingName:'',isChecked:false,showActions:false },
  { id: 2, name: 'mybatis',isEditing: false,isRename:false,editingName:'',isChecked:false,showActions:false  },
]);
// 被选中的知识点 
const selectedKnowledges = computed(() => knowledgeList.value.filter(i => i.isChecked));
//  删除知识点
const  deleteKnowledge = (knowledge) => { 
  // todo 调用后端接口删除知识点
  knowledgeList.value = knowledgeList.value.filter(i => i.id !== knowledge.id);
}
// 搜索知识点
const searchKnowledge=ref('')
 // 添加知识点的方法
const addNewKnowledge=()=>{
  console.log("添加知识点")
  const newKnowledge = { id: Date.now(), name: '',isEditing: true,isRename:false,editingName:'',isChecked:false };
  knowledgeList.value.push(newKnowledge);


}
const addKnowledgeToQuestion = () => { 
  console.log(selectedRow.value,"关联知识点弹框的确定按钮",isSyncQuestion.value)
  // todo 调用后端接口关联知识点
  knowledgeDialogVisible.value = false;
 };
  
 /******************修改题型dialog的操作**************************** */
 const  handleModifyType=()=>{
  console.log(selectedRow.value,"修改题型dialog的确定操作")
 }
 
 /******************锁定dialog的操作**************************** */
 const  handleLockOption=()=>{
  console.log(selectedRow.value,"锁定dialog的确定操作")
 }
/********************修改权限diolog操作***************************************** */
const permission=ref('public');
const allowStudentTest=ref(true);

const  handleModifyPermission=()=>{
  console.log(selectedRow.value,"修改权限dialog的确定操作")
 }
 // 处理行点击
 const handleRowClick = (row) => {
   if (row.isEditing) return; // 忽略正在编辑的行
   if (row.type === 'folder') {//如何是web-folder，则设置当前文件夹为当前行
     currentFolder.value = row;
   }else {// 如果是题目，则跳转到详情页面
    tabsStore.addTab({
      name: 'QuestionPreview',
      title: '题目预览',
    });
     router.push({ name: 'QuestionPreview', params: { id: row.id } });
   }
   
 };
 // 返回上一级
 const goBack = () => {
   if (!currentFolder.value) return;
   // 查找父文件夹
   const parentFolder = questionList.value.find(
     item => item.id === currentFolder.value.parentId && item.type === 'folder'
   );
   
   currentFolder.value = parentFolder || null;
 };
 
//表格多选框
const multipleSelection = ref([]);
const multipleTableRef = ref()
// 处理表格多选框变化
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};
// 选择的回显
const toggleSelection = (rows,ignoreSelectable) => {
  console.log(multipleTableRef.value,'aaaa');
  //  multipleTableRef.value.clearSelection()
  console.log(rows, 'rows');
   // 先清空当前选择
   if (multipleTableRef.value) {
    multipleTableRef.value.clearSelection();
  }
  if (rows&& multipleTableRef.value) {
    rows.forEach((row) => {
     multipleTableRef.value.toggleRowSelection(row,true)
    })
  
  } /*else {
    multipleTableRef.value.clearSelection()
  }*/
}
// 被选择的题目中各类题目数量
const  questionTypeCounts = computed(() => {
  const typeCount =  multipleSelection.value.reduce((acc, cur) => {
    console.log(acc,'curr',cur);
    if (cur.questionType === 'folder') return acc;
    acc[cur.questionType] = (acc[cur.questionType] || 0) + 1;
    return acc;
  }, {});
   // 转换为指定格式
  return Object.entries(typeCount).map(([questionType, count]) => ({
    questionType,
    count: String(count)
  }));
})
//选择题目的勾选状态
const  selectable = (row) => {
  if(source.value==='question') return true;
  return row.type === 'question'
}
//备选中的题目回显 
watch(() => props.selectedIds, (newVal) => {
  console.log('备选职工的ids', newVal, questionList.value);
  console.log('备选题目11', selected.value);
  // 确保表格已经渲染完成且数据已加载
  if (multipleTableRef.value && selected.value) {
    toggleSelection(selected.value);
  }
}, { immediate: true })

// 完成选题
const completeSelection = () => {
  console.log(multipleSelection.value,"完成选题",questionTypeCounts.value)
  // todo 调用后端接口完成选题
  emit('update:selectedQuestions',multipleSelection.value)
  emit('update:isSelect',true)
}
//点击了返回按钮
const  handleBack=()=>{
  emit('update:isSelect',true)
}
</script>
<style lang="less" scoped>
.right-div .el-input {
  border: 1px solid #e5e7eb;
  border-radius: 20px;
}
.right-div .el-input :deep(.el-input__wrapper) {
  background-color: #f3f4f6;
  border: none;
  border-radius: 20px;
  box-shadow: none;
}
.el-select :deep(.el-input__wrapper) {
  background-color: #f3f4f6;
  border: none;
  box-shadow: none;
}

.el-table :deep(th.el-table__cell) {
  background-color: #f9fafb;
  font-weight: 600;
}


/** 去除点击时的黑色边框 */
.el-tooltip__trigger:focus {
  outline: none; // unset 这个也行
}

.custom-header {
  .el-checkbox {
    display: flex;
    height: unset;
  }
}

</style>
